<?php

namespace App\Admin\Controllers;

use App\Models\Bank;
use App\Models\DistributiorWithdrawal;
use App\Models\Distributor;
use App\Models\Plutuspay;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Illuminate\Support\MessageBag;
use Plutuspay\Api\AccountQuery;
use Plutuspay\Api\AccountSharing;
use Plutuspay\Api\MiniPay;
use Plutuspay\Config\PayConfig;

class DistributiorWithdrawalController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '提现申请';
	protected $status = [1 => '申请', 2 => '通过', 3 => '拒绝'];
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new DistributiorWithdrawal());
        
        $grid->column('bank.bank_name', '银行');
        $grid->column('distributor.name', '名称');
        $grid->column('withdrawal_amount', __('Withdrawal amount'));
        $grid->column('status', __('Status'))->using($this->status)->dot([
        	1 => 'info', 2 => 'success', 3 => 'danger'
        ]);
        $grid->column('bank_card', __('Bank card'));
        $grid->column('created_at', __('Created at'));
        
        $grid->disableCreateButton();
        
        $grid->filter(function ($filter) {
            $filter->DisableIdFilter();
            $filter->equal('distributors_id', '分销员')->select(Distributor::all()->pluck('name', 'id'));
        });

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(DistributiorWithdrawal::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('bank_id', __('Bank id'));
        $show->field('distributors_id', __('Distributors id'));
        $show->field('withdrawal_amount', __('Withdrawal amount'));
        $show->field('status', __('Status'));
        $show->field('bank_card', __('Bank card'));
        $show->field('created_at', __('Created at'));
        $show->field('updated_at', __('Updated at'));
        $show->field('deleted_at', __('Deleted at'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new DistributiorWithdrawal());

        $form->text('bank.bank_name', '银行');
        $form->text('distributor.name', '分销员');
        $form->text('withdrawal_amount', __('Withdrawal amount'));
        $form->radio('status', __('Status'))->options([ 2 => '通过', 3 => '拒绝']);
        $form->text('bank_card', __('Bank card'));
        
        //$form->ignore(['withdrawal_amount']);
        $form->saving(function ($form) {
        	// 申请状态才能修改状态
        	if($form->model()->status != 1) {
        	    $error = new MessageBag([
			        'title'   => '提示...',
			        'message' => '已经处理过了状态了，不要重复处理....',
			    ]);
			
			    return back()->with(compact('error'));
	        }
        });
        
        $form->saved(function ($form) {
        	
        	if($form->status == 2){
        		
        	    // 提现
		        $datas=[];
				$datas['devId'] = 'FIgVcXrz';
				$datas['keyStr'] = '464967566358727a494f41656e6b574b';
				$datas['privateKey'] = config('yzpay.rsaPrivateKey');
				$datas['publicKey'] = config('yzpay.yzPublicKey');
				$datas['notifyUrl'] = 'https://ktvpjapi.isongpd.com/api/notify/receiptYzNotification';
		        $payConfig = new PayConfig($datas);
				// 查询总账户余额 余额不足不提现，提醒充值
		        $query = [
		        	'merchantId' => 188571
		        ];
		        $accountQuery = new AccountQuery($payConfig);
		        $queryRes = $accountQuery->index($query);
		        
		        if(!isset($queryRes['data']['availableBalance']) || $queryRes['data']['availableBalance'] < $form->model()->withdrawal_amount){
		            //dd('总账户余额不足请充值');
		            $error = new MessageBag([
				        'title'   => '提示...',
				        'message' => '总账户余额不足请充值....',
				    ]);
				
				    return back()->with(compact('error'));
		        }
		        // 分账接口
		        $accountSharing = new AccountSharing($payConfig);
		        // 查询接收人账号
		        // 请求参数
		        $data = [
		            'merchantId' => 188571,
			        'tradeAmount' => $form->model()->withdrawal_amount * 100,
			        'receivers' => [['merchantId' => $form->model()->distributor->merchant_id,
								        'amount' => $form->model()->withdrawal_amount * 100,
							        ]],
			        'commodityInfo' => commodityInfo([
			        	'amount' => $form->model()->withdrawal_amount * 100,
				        'id' => $form->model()->id
			        ])
		        ];

		        $res = $accountSharing->index($data);
		        
		        // 判断返回状态
		        $code = $res['code'];
		        if(!empty($res['data'])){
		            $status = $res['data']['status'];
		        } else {
		        	$status = 1;
		        }

		        //dd($res, $code, $status);
		        if($code !== $status) {
		        	// 保存请求记录到plutuspays
		        	$this->PlutuspaySave($form, $data, $res, 3);

		            $error = new MessageBag([
				        'title'   => '提示...',
				        'message' => '提现失败....',
				    ]);
					
		            $form->model()->status = 1;
		            $form->model()->save();
				    return back()->with(compact('error'));
		        } else {
		        	// 保存请求记录到plutuspays
		        	$this->PlutuspaySave($form, $data, $res, 2);

		        	$success = new MessageBag([
				        'title'   => '提示...',
				        'message' => '提现成功....',
				    ]);
				
		            return back()->with(compact('success'));
		        }
		        
	        }
        });
        
        $form->disableCreatingCheck();

        return $form;
    }
    
    // 保存请求记录
    public function PlutuspaySave($form, $data, $res, $status = 2)
    {
        // 保存请求记录到plutuspays表
        $plData = [
        	'number' => '',
	        'type' => 7, //分账提现
	        'price' => $form->model()->withdrawal_amount,
	        'user_id' => '',
	        'json' => json_encode($data),
	        'status' => $status,
	        'notify' => json_encode($res)
        ];
        Plutuspay::create($plData);
    }
}
